package com.sangeng.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sangeng.contants.SystemConstants;
import com.sangeng.entity.Menu;
import com.sangeng.mapper.MenuMapper;
import com.sangeng.service.MenuService;
import com.sangeng.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * 菜单权限表(Menu)表服务实现类
 *
 * @author makejava
 * @since 2022-08-27 14:14:03
 */
@Service("menuService")
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {
       @Autowired
    MenuService menuService;
       @Resource
       MenuMapper menuMapper;
    @Override
    public List<String> getPermsByUserId(Long id) {

        if(SecurityUtils.isAdmin()){
        LambdaQueryWrapper<Menu> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(Menu::getStatus,SystemConstants.MENU_STATUS_NORMAL);
        lambdaQueryWrapper.in(Menu::getMenuType,SystemConstants.MENU,SystemConstants.BUTTON);
        List<Menu> list = menuService.list(lambdaQueryWrapper);
            List<String> permisList = list.stream()
                    .map(menu -> menu.getPerms()).collect(Collectors.toList());
            return permisList;
                 }
       //由于业务较复杂，所以使用mabatis更简单些
       List<String> permisList = menuMapper.getPermisByUserId(id);

        return permisList;
    }

    @Override
    public List<Menu> getRouters() {

        List<Menu> menus=null;
        if(SecurityUtils.isAdmin()){
            //如果是管理员，那么显示所有的菜单
          menus = menuMapper.selectAllRouters();
        }else{
          //如果不是管理员，根据用户id去获取所拥有的菜单
          menus = menuMapper.selectRoutersByUserId(SecurityUtils.getUserId());
        }

        //构建tree
        //先找出第一层的菜单  然后去找他们的子菜单设置到children属性中
        List<Menu> menuTree = builderMenuTree(menus,0L);

        return menuTree;

    }

    private List<Menu> builderMenuTree(List<Menu> menus, long l) {
        List<Menu> menuTree = menus.stream()
                //过滤获取根菜单
                .filter(menu -> menu.getParentId().equals(l))
                .map(menu -> menu.setChildren(MenuServiceImpl.this.getChildren(menu, menus)))
                .collect(Collectors.toList());
return  menuTree;
    }
       public List<Menu>  getChildren(Menu menu2, List<Menu> menus){

           List<Menu> chidrenMenuList = menus.stream()
                   .filter(menu -> menu.getParentId().equals(menu2.getId()))
                   .collect(Collectors.toList());


return chidrenMenuList;
       }
}

